#include "md_thread.h"
#include <pthread.h>
#include <string.h>

/** 
 * @brief 创建线程并且定义栈/警戒区大小
 * @param __newthread       
 * @param istacksize             定义栈大小 如为NULL，使用默认大小    (pthraed 默认8M)
 * @param __start_routine        
 * @param __arg                 
 * 
 * @return 返回线程创建结果
 */
int md_set_stacksize_create_thread(pthread_t *__restrict __newthread,
                    size_t istacksize,
			        void *(*__start_routine) (void *),
			        void *__restrict __arg)
{
    int ierro = -1;    
    pthread_attr_t thread_attr;
    if(NULL == (void*)istacksize )
    {
        ierro = pthread_create(__newthread, NULL, __start_routine, __arg );  
        return ierro;
    }
    pthread_attr_init(&thread_attr);
    pthread_attr_setstacksize(&thread_attr, istacksize);
    ierro = pthread_create(__newthread, &thread_attr, __start_routine, __arg );  
    return ierro;
}


int md_default_create_thread(pthread_t *__restrict __newthread,
			   const pthread_attr_t *__restrict __attr,
			   void *(*__start_routine) (void *),
			   void *__restrict __arg)
{
    int ierro = -1;    
    ierro = pthread_create(__newthread, __attr, __start_routine, __arg );  
    return ierro;
}

void md_thread_exit(void *retval)
{
    return pthread_exit(retval);
}


int md_thread_mutex_init(pt_thread_mutex ptmutex_arg,char *pcname)
{
    int ierro   = -1;
    if(MUTEX_NAME_LEN   < strlen(pcname))
    {
        return -1;
    }
    strncpy(ptmutex_arg->acmutex_name,pcname,MUTEX_NAME_LEN-1);
    ptmutex_arg->acmutex_name[MUTEX_NAME_LEN-1] = 0;
    /*
    static init
    */
    //ptmutex_arg->thread_mutex   = PTHREAD_MUTEX_INITIALIZER;
    ierro = pthread_mutex_init(&(ptmutex_arg->thread_mutex),NULL);
    if(ierro    != 0)
    {
        return ierro;
    }
    return ierro;
}

int md_thread_mutex_lock(pt_thread_mutex ptmutex_arg)
{
    int ierro   = -1;
    
    ierro = pthread_mutex_lock(&(ptmutex_arg->thread_mutex));
    if(ierro    != 0)
    {
        return ierro;
    }
    ptmutex_arg->emutex_sta   = MUTEX_STA_LOCK;
    return ierro;
}

int md_thread_mutex_unlock(pt_thread_mutex ptmutex_arg)
{
    int ierro   = -1;
    ierro = pthread_mutex_unlock(&(ptmutex_arg->thread_mutex));
    if(ierro    != 0)
    {
        return ierro;
    }
    ptmutex_arg->emutex_sta   = MUTEX_STA_UNLOCK;
    return ierro;
}

int md_thread_mutex_destroy (pthread_mutex_t *__mutex)
{
    return pthread_mutex_destroy(__mutex);
}